//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入api接口
import { reqLogin, reqUserInfo } from '@/api/user'
//引入api数据类型
import type {
  loginResponseData,
} from '@/api/user/type'
import type { UserState } from './types/types'
//引入路由（常量路由）
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
//引入lodash的深拷贝方法
import cloneDeep from 'lodash/cloneDeep'
//过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(asyncRoute.children, routes) //返回已有的异步子路由在函数开头返回
      }
      return true //返回一级异步路由
    }
  })
}

//创建用户小仓库
let useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      //本地存储获取数据
      token: localStorage.getItem('TOKEN'), //用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要的数组（路由）
      username: '彦祖',
      avatar:
        'https://img2.baidu.com/it/u=1546666045,3324329771&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      // 存储当前用户是否有某一个按钮
      buttons: [],
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data: any) {
      try {
        //登录请求（调用reqLogin方法）
        let result: any = (await reqLogin(data)) as unknown as loginResponseData
        console.log('接口响应', result)
        //登录成功200->token
        //登录失败201->失败错误信息
        if (result.code === 200) {
          //pinia仓库存储一下token
          this.token = result.data.token as string
          //本地存储持久化存储数据
          localStorage.setItem('TOKEN', result.data.token as string)

          // 登录成功后，添加动态路由
          // 过滤掉不需要动态添加的路由
          const asyncRoutes = this.menuRoutes.filter((route) => {
            return !['/login', '/error404'].includes(route.path)
          })

          // 添加动态路由
          asyncRoutes.forEach((route) => {
            if (!router.hasRoute(route.name as string)) {
              router.addRoute(route)
            }
          })
          return 'ok'
        } else {
          // 登录失败
          this.token = ''
          localStorage.removeItem('TOKEN')
          return Promise.reject(new Error(result.data?.message || '登录失败'))
        }
      } catch (error) {
        // 请求异常
        // 从浏览器的 localStorage 中移除名为 TOKEN 的键值对，以确保本地不会保留错误或过期的用户认证信息。
        this.token = ''
        localStorage.removeItem('TOKEN')
        return Promise.reject(new Error('请求异常，请稍后重试'))
      }
    },
    // 退出登录
    logout() {
      this.token = ''
      this.username = ''
      this.avatar = ''
      localStorage.removeItem('TOKEN')
      // 重置路由
      this.menuRoutes.forEach((route) => {
        if (router.hasRoute(route.name as string)) {
          router.removeRoute(route.name as string)
        }
      })
    },
    //获取用户信息并存储在仓库当中
    async userInfo() {
      let result: any = await reqUserInfo()
      //如果获取用户信息成功，存储一下用户信息
      if (result.code === 200) {
        // this.username = result.data.checkUser.username
        // this.avatar = result.data.checkUser.avatar
        //获取存储相关信息
        this.username = result.data.name
        this.avatar = result.data.avatar
        this.buttons = result.data.buttons
        //计算当前用户需要展示的异步路由,需要对异步路由进行深拷贝，以防止其他用户登录时产生的路由信息相互影响
        let userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoute),
          result.data.routes,
        )
        //菜单需要的数据
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由，用户计算完毕的异步路由，任意路由需要动态添加
        userAsyncRoute.forEach((route: any) => {
          if (!router.hasRoute(route.name as string)) {
            router.addRoute(route) //添加路由
          }
        })
        // [...asyncRoute,anyRoute].forEach((route:any)=>{
        //   router.addRoute(route)
        // })
        // return 'ok';
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },

  getters: {},
})
export default useUserStore
